package com.adong.juc;

/**
 * 小练习
 */
public class Question01 {
    public static void main(String[] args) {
        Test test = new Test();


        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                try {
                    test.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "XX").start();

        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                try {
                    test.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }, "YY").start();

        //结果 : 12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z
    }
}

/*
两个线程，一个线程打印1-52，另一个打印字母A-Z打印顺序为12A34B...5152Z,
   要求用线程间通信
*/
class Test {
    int flag = 0;
    int number = 1;
    int alphabet = 65;

    public synchronized void incr() throws InterruptedException {
        // 判断,不为0等待
        while (flag != 0) {
            this.wait();
        }
        // 干活
        for (int i = 0; i < 2; i++) {
            System.out.print(number++);
        }
        flag = 1;

        // 通知
        this.notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        // 判断
        while (flag != 1) {
            this.wait();
        }
        // 干活
        flag = 0;

        System.out.print((char) alphabet);
        alphabet++;

        // 通知
        this.notifyAll();
    }
}
